import React, { useState, useRef, useEffect } from 'react';
import EmojiPicker from 'emoji-picker-react';
import './ChatArea.css';

const { ipcRenderer } = window.require('electron');

function ChatArea({ peer, messages, loadingMessages, onSendMessage, onSendFile, onStartCall }) {
  const [messageText, setMessageText] = useState('');
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const messagesEndRef = useRef(null);
  const emojiPickerRef = useRef(null);

  // Determine user status based on lastSeen timestamp
  const getUserStatus = (peer) => {
    if (!peer || !peer.lastSeen) return { status: 'offline', text: 'Offline' };

    const now = Date.now();
    const timeSinceLastSeen = now - peer.lastSeen;

    // Online: active within last 30 seconds
    if (timeSinceLastSeen < 30000) return { status: 'online', text: 'Online' };

    // Away: active within last 5 minutes
    if (timeSinceLastSeen < 300000) return { status: 'away', text: 'Away' };

    // Offline: no activity for over 5 minutes
    return { status: 'offline', text: 'Offline' };
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    // Close emoji picker when clicking outside
    const handleClickOutside = (event) => {
      if (emojiPickerRef.current && !emojiPickerRef.current.contains(event.target)) {
        setShowEmojiPicker(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSendMessage = (e) => {
    e.preventDefault();

    if (!messageText.trim()) return;

    onSendMessage(messageText, 'text');
    setMessageText('');
    setShowEmojiPicker(false);
  };

  const handleEmojiClick = (emojiObject) => {
    setMessageText(prev => prev + emojiObject.emoji);
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage(e);
    }
  };

  const handleFileSelect = async () => {
    const fileInfo = await ipcRenderer.invoke('select-file');

    if (fileInfo) {
      const fs = window.require('fs');
      const buffer = fs.readFileSync(fileInfo.path);
      const file = new File([buffer], fileInfo.name, {
        type: 'application/octet-stream'
      });

      onSendFile(file);
    }
  };

  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (!peer) {
    return (
      <div className="chat-area">
        <div className="no-chat-selected">
          <h2>Select a contact to start chatting</h2>
          <p>Choose someone from your contacts to begin a conversation</p>
        </div>
      </div>
    );
  }

  return (
    <div className="chat-area">
      <div className="chat-header">
        <div className="chat-header-info">
          <div className="chat-avatar">
            {(peer.name || 'U').charAt(0).toUpperCase()}
          </div>
          <div>
            <div className="chat-name">{peer.name || 'Unknown'}</div>
            <div className="chat-status-line">
              <div className="chat-ip">{peer.ipAddress || 'N/A'}</div>
              <span>•</span>
              <div className={`chat-status-indicator ${getUserStatus(peer).status}`}></div>
              <span className="chat-status-text">{getUserStatus(peer).text}</span>
            </div>
          </div>
        </div>

        <div className="chat-actions">
          <button
            className="action-btn"
            onClick={() => onStartCall('audio')}
            title="Voice Call"
          >
            🎤
          </button>
          <button
            className="action-btn"
            onClick={() => onStartCall('video')}
            title="Video Call"
          >
            📹
          </button>
        </div>
      </div>

      <div className="chat-messages">
        {loadingMessages ? (
          <div className="messages-loading">
            <div className="messages-loading-spinner"></div>
            <span>Loading messages...</span>
          </div>
        ) : messages.length === 0 ? (
          <div className="no-messages">
            <p>No messages yet</p>
            <small>Send a message to start the conversation</small>
          </div>
        ) : (
          messages.map((msg, index) => {
            // Determine message direction based on sender
            const isReceived = msg.from === peer.id || msg.sender_id === peer.id;
            const messageType = msg.type || msg.messageType || 'text';

            return (
              <div
                key={index}
                className={`message ${isReceived ? 'received' : 'sent'}`}
              >
                <div className="message-content">
                  {messageType === 'text' && <p>{msg.content}</p>}
                  {messageType === 'emoji' && <span className="emoji-large">{msg.content}</span>}
                </div>
                <div className="message-time">{formatTimestamp(msg.timestamp)}</div>
              </div>
            );
          })
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="chat-input-container">
        <button
          className="attach-btn"
          onClick={handleFileSelect}
          title="Attach File"
        >
          📎
        </button>

        <button
          className="emoji-btn"
          onClick={() => setShowEmojiPicker(!showEmojiPicker)}
          title="Insert Emoji"
        >
          😊
        </button>

        {showEmojiPicker && (
          <div className="emoji-picker-container" ref={emojiPickerRef}>
            <EmojiPicker onEmojiClick={handleEmojiClick} />
          </div>
        )}

        <form onSubmit={handleSendMessage} className="message-form">
          <input
            type="text"
            className="message-input"
            placeholder="Type a message..."
            value={messageText}
            onChange={(e) => setMessageText(e.target.value)}
            onKeyPress={handleKeyPress}
          />
          <button type="submit" className="send-btn">
            Send
          </button>
        </form>
      </div>
    </div>
  );
}

export default ChatArea;
